package com.atguigu.flink.chapter11.function;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/10/23 9:09
 */
public class Flink01_Function_Scalar {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<WaterSensor> stream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
        
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        Table table = tenv.fromDataStream(stream);
        
        // 1. 在table api中使用
        
        // 1.1 内联的方式
        /*table
            .select($("id"), call(MyUpperCase.class, $("id")).as("id_upper"))
            .execute()
            .print();*/
        
        // 1.2 注册后使用
        //tenv.createTemporaryFunction("toUpper", MyUpperCase.class);
        
        /*table
            .select($("id"), call("toUpper", $("id")).as("id_upper"))
            .execute()
            .print();*/
        
        // 2. 在sql语句中使用
        // 2. 1先注册
        tenv.createTemporaryFunction("toUpper", MyUpperCase.class);
        // 2.2 再使用
        
        tenv.sqlQuery("select id, toUpper(id) from " + table).execute().print();
        
        
        
    }
    
    public static class MyUpperCase extends ScalarFunction {
        public String eval(String s) {
            return s == null ? null : s.toUpperCase();
        }
    }
}
//变成大写字母的标量函数